
var pageBean = null;
var dataList = {};

$(document).ready(function(e) {
	 $(".select1").uedSelect({
			width : 345			  
	});
	$(".select2").uedSelect({
		width : 70  
	});
	$(".select3").uedSelect({
		width : 100
	});		

	$("#btnSave").click(save);
	$("#btnCancle").click(cancle);
	$("#user_add").click(add);
	
	$("#deleteusers").click(deleteUsers);
	
	$("#headerCheckBox").change(function(){
		$("INPUT[rowchecked]").prop({checked:$(this).is(':checked')});		
	});
	
	search(1);	 
});

function getRequestJson(user){	
	if(user == null){
		user = {};
	}
	var user_name = $("input[name='user_name']").val();
	if(user_name == ''){
		alert("请输入账号名称");
		return false;
	}
	user["userName"] = user_name;
	
	var userName = $("input[name='userName']").val();
	if(userName == ''){
		alert("请输入姓名");
		return false;
	}
	user["name"] = userName;	
	
	//var userGender = $("select[name='userGender']").val();
	//user["gender"] = userGender;
	
	//var age = $("input[name='age']").val();
	//user["age"] = age;
	
	var email = $("input[name='email']").val();
	user["email"] = email;
	
	var idCard = $("input[name='idCard']").val();
	user["idCard"] = idCard;
	
	var mobile = $("input[name='mobile']").val();
	if(mobile == ''){
		alert("请输入电话号码");
		return false;
	}
	user["mobile"] = mobile;
	
	var userPassword = $("input[name='userPassword']").val();
	if(userPassword == ''){
		alert("请输入密码");
		return false;
	}
	
	var rePassword = $("input[name='rePassword']").val();
	if(rePassword == ''){
		alert("请输入确认密码");
		return false;
	}
	if(userPassword != rePassword){
		alert("两次输入密码不相同，请核对后重新输入");
		return false;
	}	
	user["password"] = userPassword;
	return user;
}

function save(){	

	var requestJson = {};
	requestJson = getRequestJson(requestJson);
	if(requestJson == false){
		return false;
	}
	
	$.ajax({
        url: '/euc/user/add',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	//alert(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='user_list']").show();
            	$("DIV[name='userAdd']").hide();
            	search(pageBean.currentPage);
        	}
        	alert(datas.message);
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function update(user){
	if(user == null){
		return false;
	}
	user = getRequestJson(user);
	if(user == false){
		return false;
	}
	
	$.ajax({
        url: '/euc/user/update',
        data:JSON.stringify(user),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	if(datas.status == 0){
        		$("DIV[name='user_list']").show();
            	$("DIV[name='userAdd']").hide();
            	search(pageBean.currentPage);
        	}
        	alert(datas.message);
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function cancle(){
	$("DIV[name='user_list']").show();
	$("DIV[name='userAdd']").hide();
}

function clearForm(){
	$("input[name='user_name']").val('');
	$("input[name='userName']").val('');	
	//$("select[name='userGender']").val('男').trigger('change');	
	//$("input[name='age']").val('');
	$("input[name='email']").val('');
	$("input[name='idCard']").val('');
	$("input[name='mobile']").val('');
	$("input[name='userPassword']").val('');	
	$("input[name='rePassword']").val('');	

}

function setForm(user){
	$("input[name='user_name']").val(user.userName);
	$("input[name='userName']").val(user.name);
	//$("select[name='userGender']").val(user.gender).trigger('change');
	//$("input[name='age']").val(user.age);
	$("input[name='email']").val(user.email);
	$("input[name='idCard']").val(user.idCard);
	$("input[name='mobile']").val(user.mobile);
	$("input[name='userPassword']").val(user.password);
	$("input[name='rePassword']").val(user.password);
}

function add(){
	$("#roleOperator").html("添加");
	clearForm();
	$("input[name='user_name']").removeAttr("disabled");
	$("#btnSave").unbind();
	$("#btnSave").click(save);
	$("DIV[name='user_list']").hide();
	$("DIV[name='userAdd']").show();
}


function detail(id){
	var currentData = dataList[id];
	clearForm();
	setForm(currentData);
	$("#roleOperator").html("编辑");
	$("input[name='user_name']").attr("disabled",true);
	$("DIV[name='user_list']").hide();
	$("DIV[name='userAdd']").show();	
	$("#btnSave").unbind();
	$("#btnSave").click(function(){
		var currentData = dataList[id];
		update(currentData);
	});
}


function deleteUsers(){
	 if(confirm("确定删除选中的用户?")){
		 var result = true;
		 $("INPUT[rowchecked]:checked").each(function(index,element){
			 var id = $(element).prop("name");
			 var requestJson = {id:id};
			 $.ajax({
			        url: '/euc/user/deleteUser',
			        data:JSON.stringify(requestJson),
			        beforeSend: function(request) {
			        	var accessToken = localStorage.getItem('accessToken');
			            request.setRequestHeader("accessToken",accessToken );
			        },
			        dataType: 'JSON',
			        async: false,
			        contentType:'application/json;charset=utf-8',
			        type: 'POST',
			        success: function (result, textStatus, response) {

			        },
			        error: function () {
			        	result = false;
			        }  
			    });
		 });
		 if(result == true){
			var cur = $('.paginItem.current').find("a").html();
			cur = parseInt(cur);
			search(cur);
		 }		
	 }
}

function deleteUser(id){
	 if(confirm("确定删除该用户?")){
		var requestJson = {id:id};
		$.ajax({
	        url: '/euc/user/deleteUser',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	var cur = $('.paginItem.current').find("a").html();
				cur = parseInt(cur);
				search(cur);
				alert(result.message);
	        },
	        error: function () {
	        	console.log("error");
	        }  
	    });
	 }
}

function initailPageNumber(totalPage,currentPage,pageLength){				
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}

function search(currentPage){
			
	var parameter = $("INPUT[name='parameter']").val();
	var requestJson = {currentPage:currentPage,data:{"userName":parameter,"name":parameter,"mobile":parameter}};
		
	$.ajax({
        url: '/euc/user/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();	        	
        	$.each(result.data.list,function(i,data){
        		var html = '<tr>';
        		html += '<td style="width:30px;"><input rowchecked name="'+data.id+'" type="checkbox" value="" /></td>';
        		html += '<td style="width:70px;">' + (i+1) + '</td>';
        		html += '<td style="width:160px;">' + data.userName + '</td>';
        		html += '<td>' + data.name + '</td>';
        		//html += '<td>' + data.age + '</td>';
        		//html += '<td>' + data.gender + '</td>';
        		html += '<td>' + data.mobile + '</td>';
        		html += '<td>' + data.email + '</td>';
        		html += '<td style="width:170px;"><a href="javascript:detail('+data.id+');" class="tablelink">编辑</a>&nbsp;&nbsp;&nbsp;<a href="javascript:deleteUser('+data.id+');" class="tablelink">删除</a></td>';
        		html += '</tr>';
	        	$("#userTable").append(html);
	        	dataList[data.id] = data;
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');
        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log("error");
        }  
    });
}

